#include "registerdialog.h"
#include "global.h"
#include "httpmanager.h"
#include "registerdialog.h"
#include "ui_registerdialog.h"

#include <QDebug>

RegisterDialog::RegisterDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::RegisterDialog), m_countdown(5)
{
    ui->setupUi(this);

    ui->password_edit->setEchoMode(QLineEdit::Password);
    ui->confirm_edit->setEchoMode(QLineEdit::Password);

    ui->stackedWidget->setCurrentWidget(ui->page);

    ui->err_tip->setProperty("state", "normal");
    repolish(ui->err_tip);

    // 发送注册消息个GateServer
    connect(HttpManager::getInstance().get(), &HttpManager::signal_reg_mod_finish, this, &RegisterDialog::slot_reg_mod_finish);

    initHttpHandlers();
    ui->err_tip->clear();

    connect(ui->user_edit,&QLineEdit::editingFinished,this,[this](){
        checkUserValid();
    });

    connect(ui->email_edit, &QLineEdit::editingFinished, this, [this](){
        checkEmailValid();
    });

    connect(ui->password_edit, &QLineEdit::editingFinished, this, [this](){
        checkPasswdValid();
    });

    connect(ui->confirm_edit, &QLineEdit::editingFinished, this, [this](){
        checkConfirmValid();
    });

    connect(ui->verify_edit, &QLineEdit::editingFinished, this, [this](){
        checkVerifyValid();
    });

    // 设置鼠标浮动显示手形状
    ui->pass_visible->setCursor(Qt::PointingHandCursor);
    ui->confirm_visible->setCursor(Qt::PointingHandCursor);

    ui->pass_visible->setState("unvisible", "unvisible_hover", "", "visible",
                               "visible_hover", "");

    ui->confirm_visible->setState("unvisible", "unvisible_hover", "", "visible",
                                  "visible_hover", "");

    // 连接点击事件
    connect(ui->pass_visible, &ClickedLabel::clicked, this, [this]() {
        auto state = ui->pass_visible->getCurState();
        if (state == ClickLbState::Normal) {
            ui->password_edit->setEchoMode(QLineEdit::Password);
        } else {
            ui->password_edit->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";
    });

    connect(ui->confirm_visible, &ClickedLabel::clicked, this, [this]() {
        auto state = ui->confirm_visible->getCurState();
        if (state == ClickLbState::Normal){
            ui->confirm_edit->setEchoMode(QLineEdit::Password);
        } else {
            ui->confirm_edit->setEchoMode(QLineEdit::Normal);
        }
        qDebug() << "Label was clicked!";
    });

    m_countdown_timer = new QTimer(this);
    connect(m_countdown_timer, &QTimer::timeout, [this](){
        if (m_countdown == 0) {
            m_countdown_timer->stop();
            emit sigSwitchLogin();
            return;
        }
        -- m_countdown;
        auto str = QString("注册成功，%1 s后返回登录").arg(m_countdown);
        ui->tip_lb->setText(str);
    });
}

RegisterDialog::~RegisterDialog()
{
    qDebug() << "destruct RegisterDialog";
    delete ui;
}

// 显示错误提示
void RegisterDialog::showTip(QString str, bool b_ok)
{
    if (b_ok) {
        ui->err_tip->setProperty("state", "normal");
    } else {
        ui->err_tip->setProperty("state", "err");
    }
    ui->err_tip->setText(str);

    repolish(ui->err_tip);
}

// 初始化对应回复码的回调
void RegisterDialog::initHttpHandlers()
{
    // 注册获取验证码的回包逻辑

    // 获取验证码
    m_handlers.insert(ReqId::ID_GET_VERIFY_CODE, [this](const QJsonObject& jsonObj) {
        int error = jsonObj["error"].toInt();
        if (error != ErrorCodes::SUCCESS) {
            showTip(tr("参数错误"), false);
            return ;
        }

        auto email = jsonObj["email"].toString();
        showTip(tr("验证码已经发送到邮箱，注意查收"), true);
        qDebug() << "email is " << email;
    });

    // 注册用户
    m_handlers.insert(ReqId::ID_REG_USER, [this](QJsonObject jsonObj){
        int error = jsonObj["error"].toInt();
        if (error != ErrorCodes::SUCCESS) {
            showTip(tr("参数错误"),false);
            return;
        }
        auto email = jsonObj["email"].toString();
        showTip(tr("用户注册成功"), true);
        qDebug() << "user uid is " << jsonObj["uid"].toString();
        qDebug() << "email is " << email ;
        changeTipPage();
    });
}

// 向错误提示的容器中添加错误提示
void RegisterDialog::addTipErr(TipErr te, QString tips)
{
    m_tip_errs[te] = tips;
    showTip(tips, false);
}

// 向错误提示的容器中删除错误提示
void RegisterDialog::delTipErr(TipErr te)
{
    m_tip_errs.remove(te);
    if(m_tip_errs.empty()){
        ui->err_tip->clear();
        return;
    }

    showTip(m_tip_errs.first(), false);
}

bool RegisterDialog::checkUserValid()
{
    if(ui->user_edit->text() == ""){
        addTipErr(TipErr::TIP_USER_ERR, tr("用户名不能为空"));
        return false;
    }

    delTipErr(TipErr::TIP_USER_ERR);

    return true;
}

// 检测用户密码是否有效
bool RegisterDialog::checkPasswdValid()
{
    auto pass = ui->password_edit->text();

    if(pass.length() < 6 || pass.length() > 15){
        //提示长度不准确
        addTipErr(TipErr::TIP_PWD_ERR, tr("密码长度应为6~15"));
        return false;
    }

    // ^[a-zA-Z0-9!@#$%^&*]{6,15}$ 密码长度至少6，可以是字母、数字和特定的特殊字符
    QRegularExpression regExp("^[a-zA-Z0-9!@#$%^&*]{6,15}$");
    bool match = regExp.match(pass).hasMatch();
    if(!match){
        //提示字符非法
        addTipErr(TipErr::TIP_PWD_ERR, tr("不能包含非法字符"));
        return false;;
    }

    delTipErr(TipErr::TIP_PWD_ERR);
    return true;
}

// 检测邮箱是否有效
bool RegisterDialog::checkEmailValid()
{
    auto email = ui->email_edit->text();
    if(email.isEmpty()){
        addTipErr(TipErr::TIP_EMAIL_ERR, tr("邮箱不能为空"));
        return false;
    }

    // 邮箱地址的正则表达式
    QRegularExpression regex(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match = regex.match(email).hasMatch(); // 执行正则表达式匹配
    if(!match){
        // 提示邮箱不正确
        addTipErr(TipErr::TIP_EMAIL_ERR, tr("邮箱地址不正确"));
        return false;
    }

    delTipErr(TipErr::TIP_EMAIL_ERR);
    return true;
}

// 检测验证码是否有效
bool RegisterDialog::checkVerifyValid()
{
    auto pass = ui->verify_edit->text();
    if(pass.isEmpty()){
        addTipErr(TipErr::TIP_VARIFY_ERR, tr("验证码不能为空"));
        return false;
    }

    delTipErr(TipErr::TIP_VARIFY_ERR);
    return true;
}

// 检测验证码是否有效
bool RegisterDialog::checkConfirmValid()
{
    auto pass = ui->password_edit->text();
    auto confirm = ui->confirm_edit->text();

    if(confirm.length() < 6 || confirm.length() > 15){
        //提示长度不准确
        addTipErr(TipErr::TIP_CONFIRM_ERR, tr("密码长度应为6~15"));
        return false;
    }

    QRegularExpression regExp("^[a-zA-Z0-9!@#$%^&*]{6,15}$");
    bool match = regExp.match(confirm).hasMatch();
    if(!match){
        //提示字符非法
        addTipErr(TipErr::TIP_CONFIRM_ERR, tr("不能包含非法字符"));
        return false;;
    }

    delTipErr(TipErr::TIP_CONFIRM_ERR);

    if (pass != confirm) {
        // 提示密码不匹配
        addTipErr(TipErr::TIP_PWD_CONFIRM, tr("确认密码和输入密码不匹配"));
    } else {
        delTipErr(TipErr::TIP_PWD_CONFIRM);
    }

    return true;
}

void RegisterDialog::changeTipPage()
{
    m_countdown_timer->stop();
    ui->stackedWidget->setCurrentWidget(ui->page_2);

    // 启动定时器，设置间隔为1000毫秒（1秒）
    m_countdown_timer->start(1000);
}

// 获取注册验证码
void RegisterDialog::on_get_code_clicked()
{
    QString email = ui->email_edit->text();
    QRegularExpression reg(R"((\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+)");
    bool match = reg.match(email).hasMatch();
    if (match) {
        // 发送http验证码
        QJsonObject jsonObj;
        jsonObj["email"] = email;
        HttpManager::getInstance()->PostHttpReq(QUrl(gate_url_prefix + "/get_verifycode"),
                                            jsonObj, ReqId::ID_GET_VERIFY_CODE, Modules::REGISTERMOD);
    } else {
        showTip(tr("邮箱地址不正确"), false);
    }
}

// 处理HttpManager发送过来的注册信号
void RegisterDialog::slot_reg_mod_finish(ReqId id, QString res, ErrorCodes err)
{
    if (err != ErrorCodes::SUCCESS) {
        showTip(tr("网络请求错误......"), false);
        return ;
    }

    // 解析Json字符串，需要将res转换为QByteArray
    QJsonDocument jsonDoc = QJsonDocument::fromJson(res.toUtf8());
    // json解析错误
    if (jsonDoc.isNull()) {
        showTip(tr("json解析错误......"), false);
        return ;
    }

    if (!jsonDoc.isObject()) {
        showTip(tr("json解析错误......"), false);
        return ;
    }

    // 调用对应的回调逻辑，根据ReqId
    m_handlers[id](jsonDoc.object());
}

// 确认用户注册的槽函数，并通过http发送注册消息
void RegisterDialog::on_sure_btn_clicked()
{
    if(ui->user_edit->text() == ""){
        showTip(tr("用户名不能为空"), false);
        return;
    }

    if(ui->email_edit->text() == ""){
        showTip(tr("邮箱不能为空"), false);
        return;
    }

    if(ui->password_edit->text() == ""){
        showTip(tr("密码不能为空"), false);
        return;
    }

    if(ui->confirm_edit->text() == ""){
        showTip(tr("确认密码不能为空"), false);
        return;
    }

    if(ui->confirm_edit->text() != ui->password_edit->text()){
        showTip(tr("密码和确认密码不匹配"), false);
        return;
    }

    if(ui->verify_edit->text() == ""){
        showTip(tr("验证码不能为空"), false);
        return;
    }

    // 发送http请求注册用户
    QJsonObject json_obj;
    json_obj["user"] = ui->user_edit->text();
    json_obj["email"] = ui->email_edit->text();
    json_obj["passwd"] = xorString(ui->password_edit->text());
    json_obj["confirm"] = xorString(ui->confirm_edit->text());
    json_obj["verifycode"] = ui->verify_edit->text();
    HttpManager::getInstance()->PostHttpReq(QUrl(gate_url_prefix + "/user_register"),
                                        json_obj, ReqId::ID_REG_USER,Modules::REGISTERMOD);
}


void RegisterDialog::on_return_btn_clicked()
{
    m_countdown_timer->stop();
    emit sigSwitchLogin();
}

void RegisterDialog::on_cancel_btn_clicked()
{
    m_countdown_timer->stop();
    emit sigSwitchLogin();
}

